import cloud from '@lafjs/cloud'
import nw from 'nw-lafjs'//nw
import utils from '@/system_utils/utils'//全局方法
import sha1Func from '@/system_utils/sha1'//sha1

export default async function (ctx: FunctionContext, next: Function) {
  let now = Date.now()//当前时间

  //全局引入
  cloud.nw = nw
  cloud.utils = utils
  cloud.sha1Func = sha1Func

  // 获取请求的实际IP
  const ip = ctx.headers['x-real-ip'] ? ctx.headers['x-real-ip'] : ctx.headers['x-forwarded-for']
  if (ip == "null") {
    return utils.requestReturn({ code: 403, msg: '禁止访访问受限，请联系管理员问' })
  }
  const func = ctx.request.params.name  //函数名

  let body = ctx.body
  let query = ctx.query
  let params = ""
  if (utils.isEmptyObject(query)) {
    params = JSON.stringify(body)
  } else {
    params = JSON.stringify(query)
  }

  //ip请求
  let resp = await nw.db.findByWhereJson({
    dbName: "requestIp",
    whereJson: { ip, func }
  });
  if (resp) {
    const interval = 500;
    let isTooFast = (now - resp.create_time < interval) && (resp.func == func)
    let sameParams = (params === resp.params)
    if (isTooFast && sameParams) {
      //return utils.requestReturn({ code: 403, msg: '请求太快啦，请稍后尝试' })
    } else {
      await nw.db.update({
        dbName: "requestIp",
        whereJson: { ip, func },
        dataJson: { create_time: now, params }
      });
    }
  } else {
    await nw.db.add({
      dbName: "requestIp",
      dataJson: { ip, func, create_time: now, params },
      cancelAddTime: true
    });
  }

  //验证是否需要登录
  let noauthArr = ["noauth", "txt"]
  let isCheck = true
  for (let index = 0; index < noauthArr.length; index++) {
    const element = noauthArr[index];
    if (func.includes(element)) {
      isCheck = false
    }
  }

  if (isCheck && !ctx.user) {
    return utils.requestReturn({ code: 401, msg: '登录过期，请重新登录！' })
  }
  // 继续执行后面的云函数
  return await next(ctx)
}
